<template>
    <div class="redirect"></div>
</template>
<script setup lang="ts">
  import { useRouter, useRoute } from 'vue-router'
  import { onMounted, reactive } from 'vue'
  import type { UserListData } from '@/type/userInfo'
  import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
  import { h5login, getUsersListByOpenId, logout } from '@/api/user'
  import { setToken, setExpiresIn, getOpenId  } from '@/utils/auth'
  import { useUserInfoStore } from '@/store/userInfo'
  
  const router = useRouter()
  const route = useRoute()
  const openId:any = getOpenId()
  const userInfo:any = getLocalStorage('userInfo')
  const userListData: UserListData = reactive({
      list:[]
  })
  
  onMounted(() => {
      if(openId && userInfo) {
        usersListByOpenId(openId)
      } else {
        router.push({path:'/userCenter/userList'})
      }
  })
  
  function usersListByOpenId(openId:string) {
    getUsersListByOpenId({openId:openId}).then((res:any) => {
        const data = res.data
        userListData.list = data
        if(data && data.length == 0) {
            return router.replace({path:'/noBinding',query:{msg1:'您暂未绑定中恒云仓客户，',msg2:'请联系公司管理员扫码绑定！'}})
        }
        if(data && data.length > 0) {
          let userData:any = {hasUser:false,index:-1}
          for(let i in data) {
            if(data[i].userName === userInfo.userName) {
              userData = {
                hasUser:true,
                index:i
              }
              break
            }
          }
          if(userData.hasUser) {
            login(userData.index)
          } else {
            login(0)
          }
        }
    })
  }
  
  function login(index:number) {
    logout().then(() => {
      const data: any = userListData.list
      h5login({username:data[index].userName, password:data[index].password}).then((res: any) => {
          const data1 = res.data
          setToken(data1.access_token)
          setExpiresIn(data1.expires_in)
          setLocalStorage('userInfo',{
              userName: data[index].userName,
              avatar: data[index].avatar,
              nickName: data[index].nickName,
              shopName: data[index].shopName,
              shopId:data[index].shopId,
              issh:data[index].issh,
          })
          setLocalStorage('userListLen',data.length)
          router.replace({path:'/userCenter' }) 
      })
    })
  }
  
  
</script>
<style lang="scss" scoped>

</style>
  